<template>
  <div class="page-container" v-loading="loading">
    <el-form ref="form" :model="form" :label-width="$globalCss.formLabelWidth_default" class="flex_col flex_cell">
      <ex_header_spiler :title="$tt('label_base_info')"></ex_header_spiler>
      <ex_super_desc v-bind="baseOption" :data="form" :attrs="$defaultDetailDescAttrs" />

      <ex_header_spiler :title="$t('label_tms_waybill_task_view')">
        <template v-slot:left>
          <div class="flex_row_center">
            <div class="mg_l2">{{ $t('label_reorg_type') }}</div>
            <ex_select_auto :value="commitType" enum="ReorgOrderCommitTypeEnum" class="mg_l2" @change="changeType"
              disabled />
          </div>
        </template>

      </ex_header_spiler>
      <ex_super_table ref="table" v-bind="tableOption" :autoFlex="true" :autoPage="false" :url="detailUrl"
        :urlParams="() => ({ orderId: form.id, operateType: commitType })">
      </ex_super_table>
      <el-form-item label-width="0">
        <span>
          <!-- <el-button type="primary" @click="submit">{{ $tt('label_save') }}</el-button> -->
          <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
        </span>
      </el-form-item>
    </el-form>

    <el-dialog title="请选择SN码" :visible.sync="dialogSn" custom-class="dialog_auto">
      <div v-if="dialogSnItem">

        <el-checkbox-group :value="dialogSnTagert.snList" @input="e => snChange(dialogSnItem, dialogSnTagert, e)">
          <el-checkbox v-for="code in dialogSnItem.waitPutDownSnCodes" :label="code" :key="code"
            :disabled="snCheckDisabled(dialogSnItem, dialogSnTagert, code)">{{ code }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSn = false">取 消</el-button>
        <el-button type="primary" @click="dialogSn = false; dialogSnItem = null;">确 定</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>



<script>
import router_params from '@/mixin/router_params';
const default_form = {
  commitType: null,
  orderId: null,
  warehouseId: null,
  reorgOrderNo: null,
  detailParams: []
}
export default {
  title: 'title_reorg_operate',
  mixins: [router_params],
  components: {},
  data() {
    return {
      dialogSn: false,
      dialogSnItem: null,
      dialogSnTagert: null,
      detailUrl: '/wms-api/inside/ReorgOrderRpc/selectWaitPutDownDetail.json',

      loading: false,
      orderId: null,
      commitType: null,
      form: _.cloneDeep(default_form),

      baseOption: {
        model: [
          { key: 'orderNo', label: 'label_reorg_code', },
          { key: 'bizType', label: 'label_business_type', },
          { key: 'type', label: 'label_reorg_type', formatter: (r, c, v, i) => this.$enumShow(v, "ReorgOrderTypeEnum"), },

          { key: 'status', label: 'label_status', formatter: (r, c, v, i) => this.$enumShow(v, "ReorgOrderStatusEnum"), },
          { key: 'waitMoveOutNum', label: 'label_wait_take_down_count', },
          { key: 'waitMoveInNum', label: 'label_wait_put_count', },

          { key: 'remark', label: 'label_remark', },


          { key: 'creator', label: 'label_create_user', },
          { key: 'gmtCreate', label: 'label_create_time', formatter: (r, c, v, i) => this.$dateFormat(v) },
        ],
      },
      tableOption: {
        urlDataHandle: this.dataHandle,
        model: [
          {
            key: 'srcLocationCode', label: 'label_source_location', 'min-width': 140, if: () => !this.isPut, 'min-width': 120,
          },
          { key: 'srcContainerCode', label: 'label_source_container', 'min-width': 140, if: false, 'min-width': 100, },
          {
            key: 'srcCompartmentCode', label: 'label_box_code',
            'min-width': 140, if: () => !this.isPut && this.TOB,
          },
          { key: 'targetCompartmentCode', label: 'label_box_code', if: () => this.isPut && this.TOB, 'min-width': 140, },
          { key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': 120, },
          {
            key: 'skuName', label: 'label_sku_info', 'width': 130, 'show-overflow-tooltip': true,
            //  formatter: (r, c, v, i) => this.$formatNameCode(v, r.skuOnlyCode), 
          },
          { key: 'customerName', label: 'label_customer_name', 'width': 100, 'show-overflow-tooltip': true, },

          { key: 'isReorgContainer', label: 'label_is_full_box_move', 'width': 100, formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum"), },
          { key: 'status', label: 'label_status', 'width': 100, 'show-overflow-tooltip': true, formatter: (r, c, v, i) => this.$enumShow(v, "ReorgDetailTaskStatusEnum"), },

          {
            key: 'targetLocationCode', label: 'label_target_location', 'min-width': 140, if: () => this.isPut,
            renderHeader: (h, { column, $index }) => (<span class="table-require">{column.label}</span>),
            render: (h, { row, index, column }) => {
              if (this.disabledRow(row)) return ""
              if (_.isEmpty(row.targetList)) return ""
              // if (this.TOB) return ""
              const formItem = row.targetList.map((item, index) => {
                const value = item[column.property]
                return (
                  <base_location_select value={value} onInput={e => { this.$set(item, column.property, e) }}
                    class="w_fill"
                    checkArea={false} option={{ label: 'labelStr', value: 'code' }} />
                )
              })
              return (
                <el-form-item
                  label-width="0px"

                  prop={`detailParams.${index}.targetList`}
                  rules={this.rules.targetLocationCode}
                >
                  {formItem}
                </el-form-item>
              )
            }
          },
          {
            key: 'targetContainerCode', label: 'label_target_container', 'min-width': 140, if: false, //slot: 'targetContainerCode' 
            render: (h, { row, index, column }) => {
              if (this.disabledRow(row)) return ""
              if (_.isEmpty(row.targetList)) return ""
              if (this.TOB) return ""
              const formItem = row.targetList.map((item, index) => {
                const value = item[column.property]
                return (
                  <ex_super_input value={value}
                    class="w_fill"
                    onInput={e => {
                      this.$set(item, 'targetContainerCode', e)
                    }}
                  />
                )
              })
              return (<el-form-item
                label-width="0px"
              >
                {formItem}
              </el-form-item>)
            }
          },
          {
            key: 'targetCompartmentCode', label: 'label_target_container_grid', 'min-width': 140, if: () => false,  //slot: 'targetCompartmentCode'
            render: (h, { row }) => {
              if (this.disabledRow(row)) return ""
              if (_.isEmpty(row.targetList)) return ""
              if (this.TOB) return ""
              return (<el-form-item
                label-width="0px"
              >
                {
                  row.targetList.map((item, index) => {
                    return (
                      <ex_super_input value={item.targetCompartmentCode} onInput={e => this.$set(item, 'targetCompartmentCode', e)}
                      />
                    )
                  })
                }
              </el-form-item>)
            }
          },
          // {key: 'targetLocationCode', label: 'label_target_location', 'min-width': 140, if: () => this.isPut, 'min-width': 120,  },
          // { key: 'targetContainerCode', label: 'label_target_container', 'min-width': 140, if: () => this.isPut, 'min-width': 100, },
          // { key: 'targetCompartmentCode', label: 'label_target_container_grid', 'min-width': 140, if: () => this.isPut && !this.TOB, 'min-width': 100, },

          {
            key: 'planMoveNum', label: 'label_plan_take_down_count', if: () => !this.isPut, 'width': 120,
            // formatter: (r, c, v, i) => (this.TOB ? (v > 0 ? 1 : 0) : v)
          },
          {
            key: 'moveOutNum', label: 'label_plan_put_count', if: () => this.isPut, 'width': 120,
            // formatter: (r, c, v, i) => (this.TOB ? (v > 0 ? 1 : 0) : v)
          },
          {
            key: 'operateNum', label: 'label_operate_count', 'min-width': 120,

            render: (h, { row, index, column }) => {
              if (this.disabledRow(row)) return ""
              if (_.isEmpty(row.targetList)) return ""
              let itemForm = null
              if (this.TOB) {
                itemForm = row.targetList.map((item, index) => {
                  const isOperate = !!item.operateTime
                  const value = item[column.property]
                  const existTip = this.isPut ? this.$t('label_full_box_put') : this.$t('label_full_box_take_down')
                  const unableTip = this.$t('label_lack')
                  const inner = (<div class={isOperate ? (value > 0 ? 'color_success' : 'color_danger') : 'color_info'}>
                    {isOperate ? (value > 0 ? existTip : unableTip) : this.$t('label_wait_operate')}
                  </div>)
                  return (<el-checkbox value={value > 0 ? true : false} onChange={e => {
                    this.$set(item, 'operateTime', new Date().getTime())
                    this.$set(item, 'operateNum', e ? this.getPlanLast(row, item) : 0)
                  }}>{inner}</el-checkbox>)
                })
              } else if(this.isPut&&row.snCode){
                itemForm = row.targetList.map((item, index) => {
                  const isOperate = !!item.operateTime
                  const value = item[column.property]
                  const existTip = this.isPut ? this.$t('label_sn_put') : this.$t('label_sn_take_down')
                  const unableTip = this.$t('label_lack')
                  const inner = (<div class={isOperate ? (value > 0 ? 'color_success' : 'color_danger') : 'color_info'}>
                    {isOperate ? (value > 0 ? existTip : unableTip) : this.$t('label_wait_operate')}
                  </div>)
                  return (<el-checkbox value={value > 0 ? true : false} onChange={e => {
                    this.$set(item, 'operateTime', new Date().getTime())
                    this.$set(item, 'operateNum', e ? this.getPlanLast(row, item) : 0)
                  }}>{inner}</el-checkbox>)
                })

              } else {
                const itemFormList = row.targetList.map((item, index) => {
                  // const isOperate = !!row.operateTime
                  let selectSn = null
                  if (!_.isEmpty(row.waitPutDownSnCodes)) {
                    selectSn = (
                      <el-button type="text" class="mg_l2" onClick={e => {
                        this.dialogSn = true
                        this.dialogSnTagert = item
                        this.dialogSnItem = row
                      }} >{this.$t('SN选择')}</el-button>
                    )
                  }
                  const value = item[column.property]
                  return (
                    <div class="flex_row_center">
                      <el-input-number
                        min={item.snList.length}
                        max={this.getPlanLast(row, item)}
                        value={value}
                        class="flex_cell"
                        onInput={e => {
                          this.$set(item, 'operateTime', new Date().getTime())
                          this.$set(item, 'operateNum', e)
                        }}
                      />
                      {selectSn}
                    </div>
                  )
                })
                itemForm = (<div >
                  {itemFormList}
                </div>)
              }
              return (
                <el-form-item
                  label-width="0px"
                  prop={`detailParams.${index}.targetList`}
                  rules={this.rules.operateNum}
                >
                  {itemForm}
                </el-form-item>
              )
            },
          },
          {
            type: 'operate', width: 140,
            renderHeader: (h, { column }) => {
              return (<div class="flex_row_wrap flex_center">
                <div>{this.$t(column.label)}</div>
                {this.canBatchSubmit ? (<el-button type="primary" class="mg_l2" onClick={this.submitItemBatch}>{this.$t('label_batch_submit')}</el-button>) : null}
              </div>)
            },
            operate: [
              {
                label: 'label_submit', if: (row) => this.canSubmit(row), click: (row, i, list) => this.submitItem([row], i)
              },
              {
                label: 'label_split', if: (row) => !this.TOB && this.isPut,
                disabled: (row) => row.targetList.length >= this.getPlanLimit(row), click: (row, i, list) => {
                  row.targetList.push({
                    targetLocationCode: "",
                    targetContainerCode: "",
                    targetCompartmentCode: "",
                    operateNum: 0,
                    snList: [],
                  })
                }
              },
              {
                label: 'label_remove', class: 'button_text_warning', if: (row) => !this.TOB && this.isPut,
                disabled: (row) => row.targetList.length <= 1, click: (row, i, list) => {
                  row.targetList.pop()
                }
              },
            ]
          }
        ]
      },


      rules: {
        commitType: { message: this.$tt('tip_can_no_empty'), type: "string", required: true },


        operateNum: {
          type: 'array', required: true,
          defaultField: {
            type: "object", required: true,
            fields: {
              operateNum: [
                { message: this.$tt('tip_can_no_empty'), type: "number", required: true },
                { message: this.$tt('tip_no_less_any', { type: 0 }), type: "number", min: 0, },
              ]
            },
          },
        },
        targetLocationCode: {
          type: 'array', required: true,
          defaultField: {
            type: "object", required: true,
            fields: {
              targetLocationCode: { label: "TESTEST", message: this.$tt('tip_can_no_empty'), type: "string", required: true }
            },
          },
        },
      },
    }
  },
  computed: {
    canBatchSubmit() {
      return this.$refs.table.getData().some(it => this.canSubmit(it))
    },

    TOB() {
      return this.form.bizType == 'TOB'
    },
    isSelfCreate() {
      return this.form.createClient == 'APP'
    },
    isPut() {

      return this.commitType != 'TAKE_DOWN'
    },
  },

  methods: {
    dataHandle(res) {
      res.data.rows.forEach(it => {
        it.targetCompartmentCode = (this.TOB && !it.targetCompartmentCode) ? it.srcCompartmentCode : it.targetCompartmentCode
        it.targetLocationCodeOrg = it.targetLocationCode
        this.$set(it, 'targetList', [
          {
            targetLocationCode: it.targetLocationCode,
            targetContainerCode: it.targetContainerCode,
            targetCompartmentCode: it.targetCompartmentCode,

            operateNum: null,//this.getPlanLimit(it),
            snList: []
          }
        ])

        it.waitPutDownSnCodes = it.waitPutDownSnCodes 

      })
      this.form.detailParams = res.data.rows
      return res.data.rows
    },

    canSubmit(row) {
      return (row.targetList.some(it => !!it.operateTime)) && !this.disabledRow(row)
    },
    disabledRow(row) {
      return this.getPlanLimit(row) <= 0
    },
    getPlanLimit(row) {
      return this.isPut ? row.moveOutNum : row.planMoveNum
    },
    getOperateSum(row) {
      return _.reduce(row.targetList, (sum, it) => this.$math_add(sum, it.operateNum), 0)
    },
    getPlanLast(row, it) {
      const v = this.getPlanLimit(row) - _.reduce(row.targetList.filter(t => t != it), (sum, t) => this.$math_add(sum, t.operateNum), 0)
      return v
    },

    snCheckDisabled(row, tagert, e) {
      if (tagert.snList.some(it => it == e)) {
        return false
      } else {
        return row.targetList.some(t => t.snList.some(it => it == e))
      }
    },
    snChange(row, tagert, e) {

      if (e.length > this.getOperateSum(row)) {
        if (this.getPlanLast(row, tagert) < e.length) {
          this.$message.warning("不能大于剩余可选数量")
          return
        }
        this.$set(tagert, 'operateTime', new Date().getTime())
        this.$set(tagert, 'operateNum', e.length)
        // this.$set(row.targetList, _.findIndex(row.targetList,tagert), tagert)
      }
      this.$set(tagert, 'snList', e)
    },
    changeType(e) {
      this.commitType = e
      this.$nextTick(() => {
        this.$refs.table.loadData({})
      })
      this.fixTabLabel()
    },

    init_data_default(params) {
      // this.$nextTick(() => {
      //   this.$refs.form.setData({
      //     commitType: params.type,
      //     orderId: params.id,
      //     reorgOrderNo: params.code,
      //     detailParams: [],
      //   })
      // })
      this.orderId = params.id
      this.commitType = params.type
      // this.changeType(params.type)
      this.loading = true

      this.$ajax({
        url: "/wms-api/inside/ReorgOrderRpc/detail.json",
        method: 'post',
        data: { id: params.id, },
        success: (res) => {
          if (res && res.data) {

            this.form = Object.assign({}, _.cloneDeep(default_form), res.data)
            // this.commitType = 'PUT_AWAY'
            // if (this.form.waitMoveOutNum > 0) {
            //   this.commitType = 'TAKE_DOWN'
            // } else if (this.form.waitMoveInNum > 0) {
            //   this.commitType = 'PUT_AWAY'
            // }
            if (this.form.waitMoveOutNum <= 0 && this.form.waitMoveInNum <= 0) {
              this.return_page_back()
              return
            }
            if (this.commitType == "PUT_AWAY") {
              this.detailUrl = '/wms-api/inside/ReorgOrderRpc/selectWaitPutOnDetail.json'
            } else {
              this.detailUrl = '/wms-api/inside/ReorgOrderRpc/selectWaitPutDownDetail.json'
            }
            // this.getRemoteData(params.id)
            this.$nextTick(() => {

              this.$refs.table.loadData({})
            })
          }
          this.fixTabLabel()
        },
        complete: () => {
          this.loading = false
        }
      })
      this.fixTabLabel()
    },
    fixTabLabel() {
      if (!!this.form.orderNo) {
        this.$emit("tagModifyLabel", {
          _key: 'label_name_code', name: this.$tt(this.isPut ? 'label_reorg_put_operate' : "label_reorg_take_operate"),
          code: this.form.orderNo || ''
        })
      } else {
        this.$emit("tagModifyLabel", this.isPut ? 'label_reorg_put_operate' : "label_reorg_take_operate")
      }
    },
    // getRemoteData(e) {
    //   this.$ajax({
    //     url: "/wms-api/inside/ReorgOrderRpc/selectWaitReorgDetail.json",
    //     method: 'post',
    //     data: { orderId: this.orderId, operateType: e },
    //     success: (res) => {
    //       res.data.rows.forEach(it => {
    //         it.operateNum = 0
    //       })
    //       // this.form.detailParams = res.data.rows
    //       this.$refs.form.set("detailParams", res.data.rows)
    //       const list =
    //         _.uniqBy(res.data.rows.map(it => {
    //           return {
    //             skuOnlyCode: it.skuOnlyCode,
    //             skuName: it.skuName,
    //             customerName: it.customerName,
    //           }
    //         }), "skuOnlyCode")

    //       list.forEach(it => {
    //         it.moveSumCount = _.reduce(res.data.rows.filter(t => t.skuOnlyCode == it.skuOnlyCode), (sum, t) => (sum + t.moveOutNum), 0)
    //       })
    //       this.skuList = list
    //     }
    //   })
    // },

    submitItemBatch() {
      this.submitItem(this.$refs.table.getData())
    },
    submitItem(list, index) {

      this.$formRulesValidate({
        formRef: this.$refs['form'],
        props: list.map(row => `detailParams.${row._row_index_}.targetList`),
        success: () => {
          if (this.TOB) {
            this.submitRemote(list)
          } else {
            if (list.some(it => this.getOperateSum(it) < this.getPlanLimit(it))) {
              this.$confirm(this.$tt(this.isPut ? 'tip_putCount_less_moveCount_confirm' : 'tip_moveCount_less_planCount_confirm'), this.$tt('label_tip'), {
                type: 'warning'
              }).then(() => {
                this.submitRemote(list)
              }).catch(() => { });
            } else {
              this.submitRemote(list)
            }
          }

        },
      })

    },
    submit() {
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          let data = this.$refs.form.getFormData()
          if (!this.isPut) {
            if (data.detailParams.some(it => it.operateNum < it.planMoveNum)) {
              this.$confirm(this.$tt('tip_moveCount_less_planCount_confirm'), this.$tt('label_tip'), {
                type: 'warning'
              }).then(() => {
                this.submitRemote()
              }).catch(() => { });
            } else {
              this.submitRemote()
            }
          } else {
            if (data.detailParams.some(it => it.operateNum < it.moveOutNum)) {
              this.$confirm(this.$tt('tip_putCount_less_moveCount_confirm'), this.$tt('label_tip'), {
                type: 'warning'
              }).then(() => {
                this.submitRemote()
              }).catch(() => { });
            } else {
              this.submitRemote()
            }

          }

        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },

    submitRemote(list) {
      let submitList = []
      if (this.isPut) {
        submitList = _.flatMap(list, it => {
          const _list = it.targetList.map((item, i) => {
            return {
              id: it.id,
              bizType: it.bizType,
              skuId: it.skuId,
              skuBarcode: it.skuBarcode,
              skuOnlyCode: it.skuOnlyCode,

              targetAreaCode:item.targetAreaCode,
              targetLocationCode: item.targetLocationCode,
              targetContainerCode: item.targetContainerCode,
              targetCompartmentCode: item.targetCompartmentCode,
              moveInNum: this.TOB ? this.getPlanLimit(it) : item.operateNum,
              snList:item.snList,
            }
          })
          return _list
        })
      } else {
        submitList = _.flatMap(list, it => {
          return it.targetList.map((item, i) => {
            return {
              id: it.id,
              snList: item.snList,
              containerCode: null,
              moveOutNum: this.TOB ? this.getPlanLimit(it) : item.operateNum,
            }
          })
        })
      }
      this.loading = true
      this.$ajax({
        url: this.isPut?"/wms-api/inside/ReorgOrderRpc/pc_put_on.json":"/wms-api/inside/ReorgOrderRpc/pc_put_down.json",
        type: 'json',
        method: 'post',

        data: {
          orderId: this.form.id,
          detailParams: submitList,
        },
        success: (res) => {

          this.$message.success(this.$tt('tip_submit_success'))
          this.return_emit(null, "reload")
          // this.init_data_default({
          //   id: this.form.id,
          // })
          this.return_page_back()
          // this.return_emit(null, "reload")
          // this.refresh_data()
          // this.$tag.tagClose(null, this.intoPath)
        },
        complete: () => {
          this.loading = false

        }
      })
    }
  }

}
</script>

<style scoped></style>
